package org.micropayment.model.service.jpa;

import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import org.micropayment.model.Token;
import org.micropayment.model.service.TokenDAO;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.annotation.Propagation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;
import org.springframework.context.annotation.Scope;

/**
 *
 * @author jj
 */
@Repository("tokenDao")
@Scope("prototype")
public class JpaTokenDAO implements TokenDAO {

    private static Logger logger = LoggerFactory.getLogger(JpaTokenDAO.class);

    private EntityManager entityManager;

    @PersistenceContext
    public void setEntityManager(EntityManager entityManager) {
        this.entityManager = entityManager;
    }
    
    public Token findById(String tokenValue) {
        return entityManager.find(Token.class, tokenValue);
    }

    public List<Token> findAll() {
        Query query = 
                entityManager.createNamedQuery("Token.findAll");
        List<Token> tokens  = query.getResultList();
        return tokens;
    }

    @Transactional(readOnly=false, propagation=Propagation.REQUIRED)
    public Token save(Token token) {
        entityManager.persist(token);
        entityManager.flush();
        return token;
    }

    @Transactional(readOnly=false, propagation=Propagation.REQUIRED)
    public Token update(Token token) {
        entityManager.merge(token);
        entityManager.flush();
        return token;
    }

    @Transactional(readOnly=false, propagation=Propagation.REQUIRED)
    public boolean delete(Token token) {
        token = entityManager.getReference(Token.class, token.getTokenValue());
        if (token == null) return false;
        entityManager.remove(token);
        entityManager.flush();
        return true;
    }

    public List<Token> findList(int firstResult, int maxResults) {
        Query query = entityManager.createQuery(
                "SELECT c FROM Token c");
        query.setFirstResult(firstResult);
        query.setMaxResults(maxResults);
        List<Token> tokens = query.getResultList();
        return tokens;
    }

}